package com.example.guidedanimationdemo;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.RelativeLayout; 

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 向上滑动、双击 引导页 -- 个人中心
 * Created by xuqunxing on 2017/8/3.
 */
public class VideoDetailGuideView extends RelativeLayout {
    private Paint mPaint;
    private Paint mPaintChange;
    private Bitmap targetBitmap;
    private Bitmap handBitmap;
    private Bitmap textBitmap;
    public static int GUIDE_SHOW_TYPE_DEFAULT = 0;//向上滑动
    public static int GUIDE_SHOW_TYPE_DOUBLE = 1;//双击引导
    private int type = GUIDE_SHOW_TYPE_DEFAULT;
    private int isBelowCount;//较低的数值
    private boolean isToBottom = false;
    private boolean showWateWave = false;
    private boolean doDraw = false;//是否执行画布
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    if(!isToBottom){
                        rotation = rotation - 1;
                        if(rotation <= minRotation){
                            isBelowCount = isBelowCount + 1;
                            isToBottom = true;
                            showWateWave = true;
                        }
                    }else {
                        rotation = rotation + 1;
                        if(isBelowCount == 1){
                            if(rotation >= secondRotation){
                                isToBottom = false;
                                showWateWave = false;
                            }
                        }else {
                            if(rotation >= 0){
                                isToBottom = false;
                                showWateWave = false;
                                isBelowCount = 0;
                            ///    waveList.clear();
                               // Log.e("======","======333333-rotation:"+rotation+"--isBelowCount:"+isBelowCount);
                            }
                        }
                    }
                    flushState();
                    invalidate();
                    break;
            }
        }
    };

    private void flushState() {
        for (int i = 0; i < waveList.size(); i++) {
            Wave wave = waveList.get(i);
            wave.radius += 20 ;
            wave.alpha -= 50;
            if (wave.alpha < 0) {
                wave.alpha = 0;
            }
            wave.width -= 2;
            wave.paint.setAlpha(wave.alpha);
            wave.paint.setStrokeWidth(wave.width);
        }

    }

    public VideoDetailGuideView(Context context) {
        this(context,null);
    }

    public VideoDetailGuideView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public VideoDetailGuideView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setBackgroundColor(Color.TRANSPARENT);//要绘制一个透明的，要不然不调用onDraw
        if (mPaint == null) {
            mPaint = new Paint();
            mPaint.setAntiAlias(true);
            mPaintChange = new Paint();
            mPaintChange.setAntiAlias(true);
        }
        mPaint.setColor(Color.parseColor("#b2000000"));
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if(doDraw){
            if(type == GUIDE_SHOW_TYPE_DEFAULT){
                if (textBitmap == null) {
                    textBitmap = ((BitmapDrawable) (getResources().getDrawable(R.drawable.video_detail_guide_text))).getBitmap();
                }
                if (targetBitmap == null) {
                    targetBitmap = ((BitmapDrawable) (getResources().getDrawable(R.drawable.video_detail_guide_target1))).getBitmap();
                }
                if (handBitmap == null) {
                    handBitmap = ((BitmapDrawable) (getResources().getDrawable(R.drawable.video_detail_guide_hand1))).getBitmap();
                }
                mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
                canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), mPaint);
                if (handAniYY == 0) {
                    drawTextBitmap(canvas);
                    handX = ScreenUtil.getCurrentScreenWidth(getContext()) / 2 - handBitmap.getWidth()/3;
                    handY = ScreenUtil.getCurrentScreenHeight(getContext()) / 2 - handBitmap.getHeight();
                    Log.e("======","======000handx:"+handX+"---handY:"+handY+"--currentValue:"+currentValue);
                    drawHandBitmap(canvas);

                    targetX = ScreenUtil.getCurrentScreenWidth(getContext()) / 2 - handBitmap.getWidth()/3 - targetBitmap.getWidth() / 2;
                    targetY = ScreenUtil.getCurrentScreenHeight(getContext()) / 2 - handBitmap.getHeight()  - targetBitmap.getHeight() / 2;
                    drawTargetBitmap(canvas);
                    //  canvas.save();
                    startHandAnim();
                } else {
                    // canvas.restore();
                    drawTextBitmap(canvas);
                    drawHandBitmap(canvas);
                    drawTargetBitmap(canvas);
                }
            }else if(type == GUIDE_SHOW_TYPE_DOUBLE){
                mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
                canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), mPaint);
                if (textBitmap == null) {
                    textBitmap = ((BitmapDrawable) (getResources().getDrawable(R.drawable.video_detail_guide_double_text))).getBitmap();
                }
                if (handBitmap == null) {
                    handBitmap = ((BitmapDrawable) (getResources().getDrawable(R.drawable.video_detail_guide_hand1))).getBitmap();
                    handX = ScreenUtil.getCurrentScreenWidth(getContext()) / 2 - handBitmap.getWidth()/3;
                    handY = ScreenUtil.getCurrentScreenHeight(getContext()) / 2 - handBitmap.getHeight();
                }
                drawTextBitmap(canvas);
                drawRotateBitmap(canvas,mPaint,handBitmap,rotation,handX,handY);

                if(showWateWave){
                    int XX = handX + ScreenUtil.dip2px(getContext(),5);
                    int YY = handY  + ScreenUtil.dip2px(getContext(),5);
                    if(waveList != null){
                        Wave wave = new Wave();
                        wave.radius = 0;
                        wave.alpha = MAX_ALPHA;
                        wave.width = 10;
                        wave.xDown = XX;
                        wave.yDown = YY;
                        wave.paint = initPaint(wave.alpha, wave.width);
                        waveList.add(wave);
                    }
                }

                for (int i = 0; i < waveList.size(); i++) {
                    Wave wave2 = waveList.get(i);
                    // Log.e("======","======x:"+wave2.xDown +"---y:"+wave2.yDown+"---radius:"+wave2.radius+"--alpha:"+wave2.alpha);
                    if(wave2.alpha > 0){
                        canvas.drawCircle(wave2.xDown, wave2.yDown, wave2.radius, wave2.paint);
                    }
                }
                handler.sendEmptyMessage(0);
            }
        }
    }

    private Paint initPaint(int alpha, float width) {
        /*
         * 新建一个画笔
         */
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStrokeWidth(width);
        // 设置是环形方式绘制
        paint.setStyle(Paint.Style.STROKE);
        // System.out.println(alpha= + alpha);
        paint.setAlpha(alpha);
        // System.out.println(得到的透明度： + paint.getAlpha());
        paint.setColor(Color.WHITE);
        return paint;
    }
    private List<Wave> waveList;
    private static final int MAX_ALPHA = 255;
    private int handX;
    private int handY;
    private int targetX;
    private int targetY;
    float rotation = 0;
    float minRotation = -15;
    float secondRotation = -7;
    private void drawRotateBitmap(Canvas canvas, Paint paint, Bitmap bitmap,
                                  float rotation, float posX, float posY) {
       // Log.e("======","======rotation:"+rotation);
        Matrix matrix = new Matrix();
        int offsetX = bitmap.getWidth() / 2;
        int offsetY = bitmap.getHeight() / 2;
        matrix.postTranslate(-offsetX, -offsetY);
        matrix.postRotate(rotation);
        matrix.postTranslate(posX + offsetX, posY + offsetY);
        canvas.drawBitmap(bitmap, matrix, paint);
    }

    private void drawHandBitmap(Canvas canvas) {
        try {
            mPaintChange.setAlpha((int) (currentValue * 255));
            canvas.drawBitmap(handBitmap,
                    handX,
                    handAniYY == 0 ? handY : handAniYY, mPaintChange);
            //Log.e("======","======111handx:"+handX+"---handY:"+handAniYY+"--currentValue:"+currentValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void drawTargetBitmap(Canvas canvas) {
        try {
            mPaintChange.setAlpha((int) (currentValue * 255));
            canvas.drawBitmap(targetBitmap,
                    targetX,
                    targetAniYY == 0 ? targetY : targetAniYY, mPaintChange);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void drawTextBitmap(Canvas canvas) {
        try {
            canvas.drawBitmap(textBitmap,
                    ScreenUtil.getCurrentScreenWidth(getContext()) / 2 - textBitmap.getWidth() / 2,
                    ScreenUtil.getCurrentScreenHeight(getContext()) / 2 + textBitmap.getHeight() + ScreenUtil.dip2px(getContext(), 10), mPaint);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private float handAniYY = 0;
    private float targetAniYY = 0;
    private float currentValue = 1.0f;
    AnimatorSet set;
    public void startHandAnim() {
        try {
            set = new AnimatorSet();
            ObjectAnimator gethandTranYAnim = gethandTranYAnim();
            ObjectAnimator targetTranYAnim = getTargetTranYAnim();
            ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(handBitmap, "alpha", 1f, 0f);
            alphaAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator) {
                    currentValue = (float) valueAnimator.getAnimatedValue();
                    //Log.e("======","======currentValue:"+currentValue);
                    invalidate();
                }
            });
            gethandTranYAnim.setRepeatCount(ValueAnimator.INFINITE);
            gethandTranYAnim.setRepeatMode(ValueAnimator.INFINITE);

            targetTranYAnim.setRepeatCount(ValueAnimator.INFINITE);
            targetTranYAnim.setRepeatMode(ValueAnimator.INFINITE);

            alphaAnimator.setRepeatCount(ValueAnimator.INFINITE);
            alphaAnimator.setRepeatMode(ValueAnimator.INFINITE);
            List<Animator> animators = new ArrayList<>();
            animators.add(gethandTranYAnim);
            animators.add(targetTranYAnim);
            animators.add(alphaAnimator);
            set.playTogether(animators);
            set.setDuration(1500);
            set.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private ObjectAnimator gethandTranYAnim() {
        ObjectAnimator anim = ObjectAnimator.ofFloat(handBitmap, "translationY", handY, handY -300);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                handAniYY = (float) animation.getAnimatedValue();
               // Log.e("======","======handAniYY:"+handAniYY);
            }
        });
        return anim;
    }

    private ObjectAnimator getTargetTranYAnim() {
        ObjectAnimator anim = ObjectAnimator.ofFloat(targetBitmap, "translationY", targetY, targetY -300);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                targetAniYY = (float) animation.getAnimatedValue();
               // Log.e("======","======targetAniYY:"+targetAniYY);
            }
        });
        return anim;
    }

    public void setType(int type) {
        this.type = type;
        if(type == GUIDE_SHOW_TYPE_DOUBLE){
            waveList = Collections.synchronizedList(new ArrayList<Wave>());
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    setVisibility(GONE);
                }
            },5000);
        }
        invalidate();
    }

    public void setDoDraw(boolean doDraw) {
        this.doDraw = doDraw;
        if(!doDraw && set!= null){
            set.cancel();
        }
    }

    private class Wave {
        int waveX;
        int waveY;
        /**
         * 用来表示圆环的半径
         */
        float radius;
        Paint paint;
        /**
         * 按下的时候x坐标
         */
        int xDown;
        /**
         * 按下的时候y的坐标
         */
        int yDown;
        float width;
        int alpha;
    }
}